Skip to content

fix: multiple fixes around system stability under load #1346

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 8 commits into from
Jun 16, 2025

Conversation

nikhilsinhaparseable
Copy link
Contributor

@nikhilsinhaparseable nikhilsinhaparseable commented Jun 14, 2025

  1. perform object store sync for all streams in parallel
  2. remove restriction of multi threading to utilise all available cores
  3. add atomicity in conversion by -
  • each conversion task processes one minute of arrows 
    
  • move arrow files to inprocess folder to maintain atomicity
  • add a init sync task to process all pending files
  • add tokio sleep of 5 secs in shutdown task to let complete ongoing jobs
  • remove unwrap of write locks to avoid thread poisoning

Summary by CodeRabbit

  • New Features
    • Introduced background synchronization at server startup, ensuring data is flushed and uploaded automatically when the server initializes.
    • Enabled concurrent synchronization of multiple data streams for improved upload performance.
  • Bug Fixes
    • Enhanced error handling and logging for file access and processing, providing clearer messages and reducing missed failures.
  • Refactor
    • Streamlined file staging, grouping, and conversion with minute-based processing and improved cleanup.
    • Unified concurrency management for synchronization tasks using asynchronous task sets for smoother operation.
    • Improved internal synchronization and shutdown procedures for more reliable server behavior.
  • Style
    • Reformatted test code for improved readability without changing functionality.

Copy link
Contributor

coderabbitai bot commented Jun 14, 2025

Walkthrough

This change refactors and extends the synchronization, staging, and conversion logic for arrow and parquet files. It introduces asynchronous, per-stream synchronization using Tokio's JoinSet, enhances error handling and logging, adds minute-based grouping for file staging, and updates several method signatures and public variable visibility. Startup synchronization routines are also added.

Changes

File(s) Change Summary
src/handlers/http/health_check.rs Modified shutdown to delay before sync, renamed join set variable, updated flush_and_convert call with explicit flags, changed error log levels, replaced synchronous upload with async sync_all_streams, made SIGNAL_RECEIVED public, and removed unused warn import.
src/handlers/http/modal/query_server.rs
src/handlers/http/modal/server.rs
src/handlers/http/modal/ingest_server.rs
Added async task on server init to call sync_start, logging warnings on failure, enabling non-blocking startup synchronization.
src/parseable/staging/reader.rs Refactored error handling in file reading, replaced warning with error logs, streamlined control flow, and removed unused warn import.
src/parseable/streams.rs Major refactor: introduced minute-based inprocess staging, added/updated grouping and conversion methods, improved error handling, updated metrics, changed method signatures, added new helper methods, removed unused imports, and updated tests for new signatures.
src/storage/object_storage.rs Refactored upload_files_from_staging to operate per-stream, added stream_name parameter, improved logging and metrics, introduced sync_all_streams for concurrent per-stream uploads using JoinSet.
src/sync.rs Refactored sync logic to use JoinSet for concurrent tasks, improved logging and error handling, added sync_start async function for startup sync, updated function signatures, removed explicit worker thread count in runtime macro.
src/otel/traces.rs Reformatted test macros and struct initializations for improved readability without changing logic or assertions. Removed trailing blank line before test module.

Sequence Diagram(s)

sequenceDiagram
    participant Server
    participant SyncModule
    participant Streams
    participant ObjectStorage

    Server->>+SyncModule: sync_start()
    SyncModule->>+Streams: flush_and_convert(init_signal=true, shutdown_signal=false)
    Streams-->>-SyncModule: Result
    SyncModule->>+ObjectStorage: sync_all_streams(joinset)
    ObjectStorage->>+ObjectStorage: upload_files_from_staging(stream_name) (per stream, concurrent)
    ObjectStorage-->>-SyncModule: Result (per stream)
    SyncModule-->>-Server: Result
Loading

Possibly related PRs

Suggested labels

for next release

Poem

A rabbit hops through code so neat,
Async tasks now skip and fleet.
Streams group by minute, logs are bright,
Errors handled left and right.
With every sync, the files align—
Parquet and Arrow, all in line!
🐇✨


📜 Recent review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 1d92e04 and f020c6b.

📒 Files selected for processing (3)
  • src/handlers/http/modal/ingest_server.rs (3 hunks)
  • src/handlers/http/modal/query_server.rs (3 hunks)
  • src/handlers/http/modal/server.rs (3 hunks)
🚧 Files skipped from review as they are similar to previous changes (3)
  • src/handlers/http/modal/query_server.rs
  • src/handlers/http/modal/server.rs
  • src/handlers/http/modal/ingest_server.rs
⏰ Context from checks skipped due to timeout of 90000ms (10)
  • GitHub Check: coverage
  • GitHub Check: Quest Smoke and Load Tests for Distributed deployments
  • GitHub Check: Quest Smoke and Load Tests for Standalone deployments
  • GitHub Check: Build Default x86_64-apple-darwin
  • GitHub Check: Build Kafka x86_64-unknown-linux-gnu
  • GitHub Check: Build Default aarch64-unknown-linux-gnu
  • GitHub Check: Build Default aarch64-apple-darwin
  • GitHub Check: Build Kafka aarch64-apple-darwin
  • GitHub Check: Build Default x86_64-pc-windows-msvc
  • GitHub Check: Build Default x86_64-unknown-linux-gnu
✨ Finishing Touches
  • 📝 Generate Docstrings

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Explain this complex logic.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai explain this code block.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and explain its main purpose.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Support

Need help? Create a ticket on our support page for assistance with any issues or questions.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate docstrings to generate docstrings for this PR.
  • @coderabbitai generate sequence diagram to generate a sequence diagram of the changes in this PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 4

🔭 Outside diff range comments (1)
src/parseable/streams.rs (1)

345-353: ⚠️ Potential issue

File::created() will panic on common Linux filesystems

std::fs::Metadata::created() is not implemented on most Unix filesystems and returns an error.
The expect("Creation time should be accessible") will therefore bring the whole conversion task – and potentially the server – down on virtually every Linux deployment.

Replace with a fall-back that relies on the consistently available modified() timestamp (or skip the filtering when created() is unsupported).

- let creation = path.metadata()?.created().expect("Creation time should be accessible");
+ let creation = path
+     .metadata()?
+     .created()
+     .or_else(|_| path.metadata()?.modified())?; // fallback
♻️ Duplicate comments (1)
src/handlers/http/modal/server.rs (1)

126-131: Startup sync duplication

Same concern as in query_server.rs: this detached sync_start() may overlap with the periodic sync::handler spawned just below.
Verify that the two paths cannot run concurrently or gate them behind a single-execution guard.

🧹 Nitpick comments (6)
src/handlers/http/modal/query_server.rs (1)

131-136: Possible duplicate & unmanaged sync task

sync_start() is fired here while a separate periodic sync thread (sync::handler) is launched a few lines later.
Without a guard this can lead to two independent object-store uploads running simultaneously, wasting IO and increasing race-surface.
Consider:

  1. Running the startup sync inside the periodic worker before its main loop begins, or
  2. Protecting concurrent runs with a mutex/atomic “sync-in-progress” flag, and/or
  3. At least keep the JoinHandle so it can be awaited during shutdown.
src/parseable/staging/reader.rs (1)

88-103: Great improvement, but one remaining unwrap still panics

The new match File::open keeps the reader resilient – nice.
However the earlier file.metadata().unwrap() (line 51) will still crash the entire process for an I/O error (e.g. permission issue).
Replace with a fallible path similar to this block and skip the file on failure.

src/handlers/http/health_check.rs (1)

63-65: Hard-coded 5 s sleep may stall graceful shutdown

A fixed sleep(5s) delays shutdown even when no in-flight requests exist and also blocks all new requests (flag is already set).
Consider making this configurable or replacing with a loop that waits until active-request-counter drops to zero (with max timeout).

src/parseable/streams.rs (2)

70-77: arrow_path_to_parquet argument order is confusing

staging_path is expected to be a directory, yet tests pass a file path.
Consider tightening the contract:

-fn arrow_path_to_parquet(staging_path: &Path, path: &Path, random_string: &str)
+fn arrow_path_to_parquet(staging_dir: &Path, arrow_file: &Path, random_string: &str)

and add an early debug_assert!(staging_dir.is_dir()) to prevent accidental misuse.
This will avoid silently generating paths like /some/file.arrows/<name>.parquet.


588-604: Metric update panics on I/O errors

file.metadata().unwrap() will panic on any transient I/O failure.
Prefer if let Ok(meta) = file.metadata() to keep the sync path resilient under load.

src/sync.rs (1)

155-161: JoinSet drain duplicates log code – factor into helper

The same success / failure logging block appears three times in this file.
Extracting a small helper (log_join_result(res, "object store sync")) will remove repetition and keep future fixes in one spot.

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 970a5a5 and 42d27d0.

📒 Files selected for processing (7)
  • src/handlers/http/health_check.rs (2 hunks)
  • src/handlers/http/modal/query_server.rs (2 hunks)
  • src/handlers/http/modal/server.rs (2 hunks)
  • src/parseable/staging/reader.rs (2 hunks)
  • src/parseable/streams.rs (24 hunks)
  • src/storage/object_storage.rs (2 hunks)
  • src/sync.rs (7 hunks)
🧰 Additional context used
🧬 Code Graph Analysis (2)
src/handlers/http/modal/query_server.rs (1)
src/sync.rs (1)
  • sync_start (248-271)
src/handlers/http/modal/server.rs (1)
src/sync.rs (1)
  • sync_start (248-271)
⏰ Context from checks skipped due to timeout of 90000ms (10)
  • GitHub Check: Build Default x86_64-pc-windows-msvc
  • GitHub Check: Build Default aarch64-unknown-linux-gnu
  • GitHub Check: Build Default aarch64-apple-darwin
  • GitHub Check: Build Default x86_64-apple-darwin
  • GitHub Check: Build Default x86_64-unknown-linux-gnu
  • GitHub Check: Build Kafka x86_64-unknown-linux-gnu
  • GitHub Check: Build Kafka aarch64-apple-darwin
  • GitHub Check: coverage
  • GitHub Check: Quest Smoke and Load Tests for Standalone deployments
  • GitHub Check: Quest Smoke and Load Tests for Distributed deployments
🔇 Additional comments (2)
src/sync.rs (2)

79-82: Re-consider spawning a fresh Tokio runtime here

handler is annotated with #[tokio::main], and the crate already defines another
#[tokio::main] (alert_runtime). Each call spins up a stand-alone multi-thread
runtime, which is expensive and prevents reuse of the global IO driver.

If handler is invoked from within an existing runtime (e.g. Actix), switch to
tokio::spawn + async fn instead of a second #[tokio::main].


247-271: Startup sync may run concurrently with periodic sync

sync_start() performs a full flush + upload but does not coordinate with the
long-running local_sync / object_store_sync loops. If startup takes longer than
LOCAL_SYNC_INTERVAL, you can end up with overlapping conversions on the same stream.

Consider signalling completion (e.g. a OnceCell flag) before enabling the periodic
tasks, or make the periodic loops wait on sync_start’s JoinHandle.

coderabbitai[bot]
coderabbitai bot previously approved these changes Jun 16, 2025
Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 2

🧹 Nitpick comments (4)
src/sync.rs (4)

131-144: Potential starvation & duplicated code around JoinSet loop

Every tick builds a fresh JoinSet, fires sync_all_streams, then blocks until all joins resolve.
If a large backlog exists, the loop may overrun the next tick, defeating periodic behaviour.

Consider extracting the common “spawn, join, log” logic used here and in local_sync into a reusable helper that:

  1. Re-uses a single JoinSet (or a bounded one) across ticks, or
  2. Offloads joins into a detached task so the driving loop never stalls.

This will keep upload cadence predictable and DRY-up the nearly identical code in the two sync paths.


195-207: Duplicate flush/convert scaffold – factor out to avoid divergence

The block mirrors lines 131-144 almost verbatim (different callback only). If a bug fix is needed later you’ll have to patch two places.

Extract into something like:

async fn run_and_log<F>(name: &str, threshold: Duration, f: F)
where
    F: FnOnce(&mut JoinSet<()>) + Send + 'static,
{}

and call it from both locations.


238-264: sync_start runs heavy IO on the main thread during startup

sync_start() performs full flush + upload synchronously before returning. On large datasets this can delay server readiness and make liveness probes fail.

Introduce either:

• a “started but warming up” state exposed via health-check, or
• run this in the background and let the server accept traffic immediately (with proper back-pressure).

Also consider making the 15 s threshold configurable – real-world clusters may legitimately take longer.


269-278: Minor: inconsistent log levels

log_join_result() logs success with info!, failures with warn!, and join errors with error!.
You may want to promote task failures (Ok(Err(_))) to error! as well to ease alerting.

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 7416b7a and d453c7d.

📒 Files selected for processing (1)
  • src/sync.rs (6 hunks)
⏰ Context from checks skipped due to timeout of 90000ms (10)
  • GitHub Check: Build Default x86_64-apple-darwin
  • GitHub Check: Build Default x86_64-pc-windows-msvc
  • GitHub Check: Build Default aarch64-apple-darwin
  • GitHub Check: Build Default aarch64-unknown-linux-gnu
  • GitHub Check: Quest Smoke and Load Tests for Standalone deployments
  • GitHub Check: Build Default x86_64-unknown-linux-gnu
  • GitHub Check: Quest Smoke and Load Tests for Distributed deployments
  • GitHub Check: Build Kafka aarch64-apple-darwin
  • GitHub Check: Build Kafka x86_64-unknown-linux-gnu
  • GitHub Check: coverage

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 2

🧹 Nitpick comments (2)
src/sync.rs (1)

131-145: Consider graceful early-exit for still-running JoinSet tasks

If inbox_rx receives a shutdown signal while sync_all_streams is in progress, any in-flight uploads inside joinset keep running until completion because the JoinSet lives only inside this closure.
In practice that is fine, but you lose the option to abort quickly during shutdown or when the monitor times out.

A lightweight pattern is to call joinset.shutdown().await; before the while let Some(..) loop, which causes unfinished tasks to be aborted and immediately joined:

-                                let mut joinset = JoinSet::new();
+                                let mut joinset = JoinSet::new();

                                 sync_all_streams(&mut joinset);

+                                // Abort remaining tasks if the outer future is cancelled
+                                joinset.shutdown().await;
                                 while let Some(res) = joinset.join_next().await {
                                     log_join_result(res, "object store sync");
                                 }

This avoids dangling uploads during shutdown and keeps task lifetimes explicit.

src/parseable/streams.rs (1)

380-387: Cross-device rename can fail – fall back to copy/remove

fs::rename fails with EXDEV if the staging disk and the in-process directory reside on
different mounts (common in containerised setups with bind-mounts).
Handle that case explicitly:

-                    if let Err(e) = fs::rename(&arrow_file_path, &new_path) {
+                    if let Err(e) = fs::rename(&arrow_file_path, &new_path) {
                         error!(
                             "Failed to rename arrow file to inprocess directory: {} -> {}: {e}",
                             arrow_file_path.display(),
                             new_path.display()
                         );
+                        if e.kind() == std::io::ErrorKind::CrossDeviceLink {
+                            if let Err(copy_err) = fs::copy(&arrow_file_path, &new_path) {
+                                error!("Copy fallback also failed: {copy_err}");
+                            } else {
+                                let _ = remove_file(&arrow_file_path);
+                        }
                     }

This prevents the entire batch from stalling on heterogeneous storage layouts.

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between d453c7d and 0cb81b6.

📒 Files selected for processing (7)
  • src/handlers/http/health_check.rs (2 hunks)
  • src/handlers/http/modal/query_server.rs (2 hunks)
  • src/handlers/http/modal/server.rs (2 hunks)
  • src/parseable/staging/reader.rs (3 hunks)
  • src/parseable/streams.rs (22 hunks)
  • src/storage/object_storage.rs (2 hunks)
  • src/sync.rs (6 hunks)
🚧 Files skipped from review as they are similar to previous changes (5)
  • src/handlers/http/modal/query_server.rs
  • src/handlers/http/modal/server.rs
  • src/handlers/http/health_check.rs
  • src/parseable/staging/reader.rs
  • src/storage/object_storage.rs
🧰 Additional context used
🧠 Learnings (1)
src/sync.rs (1)
Learnt from: nikhilsinhaparseable
PR: parseablehq/parseable#1346
File: src/sync.rs:78-83
Timestamp: 2025-06-16T04:56:21.596Z
Learning: In Rust async code, `#[tokio::main]` is appropriate when functions are called from separate OS threads (like `thread::spawn()`), as it creates a new Tokio runtime for that thread. The "Cannot start a runtime from within a runtime" error only occurs when `#[tokio::main]` functions are called from within an existing Tokio runtime context.
🧬 Code Graph Analysis (1)
src/sync.rs (2)
src/storage/object_storage.rs (1)
  • sync_all_streams (878-897)
src/parseable/streams.rs (3)
  • new (109-126)
  • flush_and_convert (951-973)
  • flush_and_convert (1047-1062)
⏰ Context from checks skipped due to timeout of 90000ms (7)
  • GitHub Check: Quest Smoke and Load Tests for Standalone deployments
  • GitHub Check: Quest Smoke and Load Tests for Distributed deployments
  • GitHub Check: coverage
  • GitHub Check: Build Default x86_64-unknown-linux-gnu
  • GitHub Check: Build Default x86_64-pc-windows-msvc
  • GitHub Check: Build Default aarch64-unknown-linux-gnu
  • GitHub Check: Build Kafka x86_64-unknown-linux-gnu

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1

🧹 Nitpick comments (2)
src/parseable/streams.rs (2)

69-84: arrow_path_to_parquet trusts stream_staging_path is a directory

parquet_path.push(filename_with_random_number) silently produces paths like
/tmp/myfile.arrows/<generated>.parquet when stream_staging_path is accidentally a
file (the current unit-tests pass such a path).
At runtime this is unlikely, but if it happens the rename that follows will fail with
Not a directory.

-    let mut parquet_path = stream_staging_path.to_owned();
-    parquet_path.push(filename_with_random_number);
+    // Guard against a file being passed instead of the staging directory.
+    let mut parquet_path = if stream_staging_path.is_dir() {
+        stream_staging_path.to_path_buf()
+    } else {
+        stream_staging_path
+            .parent()
+            .unwrap_or_else(|| Path::new("."))
+            .to_path_buf()
+    };
+    parquet_path.push(filename_with_random_number);

This keeps the function robust and lets the unit-tests keep their current call-site.


585-593: Metrics reset only clears “arrows”/“parquet” buckets

The helper zeroes STAGING_FILES and both STORAGE_SIZE gauges, but only for the
labels "arrows" and "parquet". If a future extension introduces another label
(e.g. "orc"), the metrics will become stale. Consider looping through
metrics::STORAGE_SIZE.collect() and clearing every entry for the current stream.

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 0cb81b6 and 4c95dc6.

📒 Files selected for processing (2)
  • src/otel/traces.rs (12 hunks)
  • src/parseable/streams.rs (22 hunks)
✅ Files skipped from review due to trivial changes (1)
  • src/otel/traces.rs
🧰 Additional context used
🧠 Learnings (1)
src/parseable/streams.rs (1)
Learnt from: nikhilsinhaparseable
PR: parseablehq/parseable#1346
File: src/parseable/streams.rs:351-355
Timestamp: 2025-06-16T05:20:18.557Z
Learning: In the Parseable codebase, arrow files are expected to always have valid creation or modified timestamps as a basic system assumption. The conversion flow uses expect() on file metadata operations to enforce this invariant with fail-fast behavior rather than graceful error handling, as violations represent fundamental system issues that should cause immediate failures.
⏰ Context from checks skipped due to timeout of 90000ms (10)
  • GitHub Check: Quest Smoke and Load Tests for Standalone deployments
  • GitHub Check: Quest Smoke and Load Tests for Distributed deployments
  • GitHub Check: coverage
  • GitHub Check: Build Default aarch64-apple-darwin
  • GitHub Check: Build Default x86_64-unknown-linux-gnu
  • GitHub Check: Build Default x86_64-pc-windows-msvc
  • GitHub Check: Build Default x86_64-apple-darwin
  • GitHub Check: Build Default aarch64-unknown-linux-gnu
  • GitHub Check: Build Kafka x86_64-unknown-linux-gnu
  • GitHub Check: Build Kafka aarch64-apple-darwin
🔇 Additional comments (2)
src/parseable/streams.rs (2)

717-723: Hard-coded label mismatch may skew storage metrics

Here the label is ARROW_FILE_EXTENSION, while update_staging_metrics uses the
literal string "arrows". If the constant ever diverges (e.g. "arrow"), metrics
for deletions and additions will land in different time-series.

Validate that ARROW_FILE_EXTENSION is exactly "arrows" or unify both call-sites
to the same constant.


140-149: 👍 Graceful recovery from poisoned mutex

Great call replacing the immediate panic with a warning and into_inner()
this prevents a single thread panic from killing ingestion on the whole stream.

coderabbitai[bot]
coderabbitai bot previously approved these changes Jun 16, 2025
1. perform object store sync for all streams in parallel
2. remove restriction of multi threading to utilise all available cores
3. add atomicity in conversion by -
    i. each conversion task processes one minute of arrows
   ii. move arrow files to inprocess folder to maintain atomicity
  iii. add a init sync task to process all pending files
   iv. add tokio sleep of 5 secs in shutdown task to let complete ongoing jobs
    v. remove unwrap of write locks to avoid thread poisoning
Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1

♻️ Duplicate comments (1)
src/parseable/streams.rs (1)

687-706: Opening the .part file with append(true) is still fragile
(see previous discussion – unchanged)

If a stale .part file survives a crash, the next run will silently append new
bytes, producing an invalid parquet footer. Using truncate(true) avoids this
edge case at zero cost.

-    let mut part_file = OpenOptions::new()
-        .create(true)
-        .append(true)
+    let mut part_file = OpenOptions::new()
+        .write(true)
+        .create(true)
+        .truncate(true)
🧹 Nitpick comments (4)
src/sync.rs (1)

119-145: Avoid the extra tokio::spawn indirection – run the interval loop directly

Spawning a second task inside the already-spawned handle adds an unnecessary layer of scheduling, makes panic/ cancellation semantics harder to reason about, and forces the surrounding catch_unwind dance.

You can drop the inner tokio::spawn and execute the interval loop in the outer task itself:

-    let result = tokio::spawn(async move {
-        let mut sync_interval = interval_at(next_minute(), STORAGE_UPLOAD_INTERVAL);
-        ...
-    });
-
-    match AssertUnwindSafe(result).catch_unwind().await {
+    let result = AssertUnwindSafe(async move {
+        let mut sync_interval = interval_at(next_minute(), STORAGE_UPLOAD_INTERVAL);
+        ...
+    })
+    .catch_unwind()
+    .await;
+
+    match result {
         Ok(_) => { /* handled below */ }

This keeps the same panic protection while removing one level of indirection.

src/parseable/streams.rs (3)

72-86: arrow_path_to_parquet first parameter is a directory, but tests pass a file path

stream_staging_path is expected to be the stream’s staging directory (self.data_path).
Passing the full arrow file path (as the unit-tests currently do) yields a nonsensical output like:

/tmp/arrow_file_path/converted_name.parquet

Consider renaming the parameter to staging_dir and fixing the tests to call:

arrow_path_to_parquet(file_path.parent().unwrap(), &file_path, random)

to reflect real-world usage.


210-223: arrow_files() does an O(n) metadata stat per file every tick

Calling metadata() for each entry on every sync cycle can become costly when tens-of-thousands of files accumulate.

If ordering by mtime is not strictly required, drop the sort & metadata hit.
If ordering is needed, cache the (PathBuf, SystemTime) vector once per run of convert_disk_files_to_parquet instead of on every directory scan.


263-288: Single minute directory may mix older arrow files – revisit atomicity guarantee

arrow_files_grouped_exclude_time moves all eligible files—regardless of their
original minute—into a directory named processing_<current-minute-1>.
Files that are >1 minute old therefore get grouped together, breaking the
“one-minute-per-conversion-task” invariant described in the design docs.

Either create the directory using each file’s own minute or keep per-minute
sub-directories when doing the move.

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 4c95dc6 and 70ca26d.

📒 Files selected for processing (8)
  • src/handlers/http/health_check.rs (2 hunks)
  • src/handlers/http/modal/query_server.rs (2 hunks)
  • src/handlers/http/modal/server.rs (2 hunks)
  • src/otel/traces.rs (12 hunks)
  • src/parseable/staging/reader.rs (3 hunks)
  • src/parseable/streams.rs (22 hunks)
  • src/storage/object_storage.rs (2 hunks)
  • src/sync.rs (6 hunks)
🚧 Files skipped from review as they are similar to previous changes (6)
  • src/otel/traces.rs
  • src/handlers/http/modal/query_server.rs
  • src/handlers/http/modal/server.rs
  • src/handlers/http/health_check.rs
  • src/parseable/staging/reader.rs
  • src/storage/object_storage.rs
🧰 Additional context used
🧠 Learnings (2)
src/sync.rs (1)
Learnt from: nikhilsinhaparseable
PR: parseablehq/parseable#1346
File: src/sync.rs:78-83
Timestamp: 2025-06-16T04:56:21.596Z
Learning: In Rust async code, `#[tokio::main]` is appropriate when functions are called from separate OS threads (like `thread::spawn()`), as it creates a new Tokio runtime for that thread. The "Cannot start a runtime from within a runtime" error only occurs when `#[tokio::main]` functions are called from within an existing Tokio runtime context.
src/parseable/streams.rs (2)
Learnt from: nikhilsinhaparseable
PR: parseablehq/parseable#1346
File: src/parseable/streams.rs:351-355
Timestamp: 2025-06-16T05:20:18.557Z
Learning: In the Parseable codebase, arrow files are expected to always have valid creation or modified timestamps as a basic system assumption. The conversion flow uses expect() on file metadata operations to enforce this invariant with fail-fast behavior rather than graceful error handling, as violations represent fundamental system issues that should cause immediate failures.
Learnt from: nikhilsinhaparseable
PR: parseablehq/parseable#1346
File: src/parseable/streams.rs:680-686
Timestamp: 2025-06-16T05:30:13.360Z
Learning: The parquet conversion system uses a minute-based atomic design where each conversion task operates on different sets of arrow files moved to timestamped "inprocess_" directories, ensuring no conflicts between tasks and no retry mechanisms that could cause file corruption.
⏰ Context from checks skipped due to timeout of 90000ms (10)
  • GitHub Check: coverage
  • GitHub Check: Build Default x86_64-apple-darwin
  • GitHub Check: Build Default x86_64-pc-windows-msvc
  • GitHub Check: Build Default aarch64-apple-darwin
  • GitHub Check: Build Default aarch64-unknown-linux-gnu
  • GitHub Check: Build Kafka aarch64-apple-darwin
  • GitHub Check: Build Default x86_64-unknown-linux-gnu
  • GitHub Check: Build Kafka x86_64-unknown-linux-gnu
  • GitHub Check: Quest Smoke and Load Tests for Standalone deployments
  • GitHub Check: Quest Smoke and Load Tests for Distributed deployments

Comment on lines +319 to +331
fn get_node_id_string(&self) -> String {
match self.options.mode {
Mode::Query => QUERIER_META
.get()
.map(|querier_metadata| querier_metadata.get_node_id())
.expect("Querier metadata should be set"),
Mode::Ingest => INGESTOR_META
.get()
.map(|ingestor_metadata| ingestor_metadata.get_node_id())
.expect("Ingestor metadata should be set"),
_ => "000000000000000".to_string(),
}
}
Copy link
Contributor

@coderabbitai coderabbitai bot Jun 16, 2025

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue

get_node_id_string() will panic when the global meta isn’t initialised

Both QUERIER_META.get() and INGESTOR_META.get() are .expect()ed.
Any early invocation (e.g. during startup sync before the gRPC registration code runs) will crash the thread.

Return a fallback ID instead of panicking:

-Mode::Query => QUERIER_META.get().map(|m| m.get_node_id()).expect("…"),
+Mode::Query => QUERIER_META
+        .get()
+        .map(|m| m.get_node_id())
+        .unwrap_or_else(|| "000000000000000".to_string()),

Same for the ingest path.

📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
fn get_node_id_string(&self) -> String {
match self.options.mode {
Mode::Query => QUERIER_META
.get()
.map(|querier_metadata| querier_metadata.get_node_id())
.expect("Querier metadata should be set"),
Mode::Ingest => INGESTOR_META
.get()
.map(|ingestor_metadata| ingestor_metadata.get_node_id())
.expect("Ingestor metadata should be set"),
_ => "000000000000000".to_string(),
}
}
fn get_node_id_string(&self) -> String {
match self.options.mode {
Mode::Query => QUERIER_META
.get()
.map(|m| m.get_node_id())
.unwrap_or_else(|| "000000000000000".to_string()),
Mode::Ingest => INGESTOR_META
.get()
.map(|m| m.get_node_id())
.unwrap_or_else(|| "000000000000000".to_string()),
_ => "000000000000000".to_string(),
}
}
🤖 Prompt for AI Agents
In src/parseable/streams.rs around lines 319 to 331, the get_node_id_string()
function uses expect() on QUERIER_META.get() and INGESTOR_META.get(), which
causes a panic if the global metadata is not initialized. To fix this, replace
the expect() calls with code that returns a fallback node ID string when the
metadata is not set, avoiding panics during early startup or uninitialized
states.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Ingest or Query mode will always have a node_id, node_id is generated at the server initialisation itself

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@nikhilsinhaparseable, thank you for the clarification! I understand that the server initialization process ensures the node_id is available before this code path is executed, making the .expect() calls safe in this context.


✏️ Learnings added
Learnt from: nikhilsinhaparseable
PR: parseablehq/parseable#1346
File: src/parseable/streams.rs:319-331
Timestamp: 2025-06-16T09:50:38.623Z
Learning: In Parseable's Ingest or Query mode, the node_id is always available because it's generated during server initialization itself, before the get_node_id_string() function in streams.rs would be called. This makes the .expect() calls on QUERIER_META.get() and INGESTOR_META.get() safe in this context.

Note: Learnings are effective only in the context of similar code segments. To apply general coding guidelines, please configure review instructions. You can manage existing learnings in the app.

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 70ca26d and 1d92e04.

📒 Files selected for processing (1)
  • src/handlers/http/modal/ingest_server.rs (2 hunks)
🧰 Additional context used
🧬 Code Graph Analysis (1)
src/handlers/http/modal/ingest_server.rs (1)
src/sync.rs (1)
  • sync_start (243-271)
⏰ Context from checks skipped due to timeout of 90000ms (10)
  • GitHub Check: Quest Smoke and Load Tests for Distributed deployments
  • GitHub Check: Quest Smoke and Load Tests for Standalone deployments
  • GitHub Check: coverage
  • GitHub Check: Build Default x86_64-pc-windows-msvc
  • GitHub Check: Build Default aarch64-apple-darwin
  • GitHub Check: Build Default x86_64-apple-darwin
  • GitHub Check: Build Default x86_64-unknown-linux-gnu
  • GitHub Check: Build Kafka x86_64-unknown-linux-gnu
  • GitHub Check: Build Default aarch64-unknown-linux-gnu
  • GitHub Check: Build Kafka aarch64-apple-darwin

@nitisht nitisht merged commit cfd1348 into parseablehq:main Jun 16, 2025
14 checks passed
@nitisht
Copy link
Member

nitisht commented Jun 16, 2025

Fixes #1341

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants